package com.ithuameng.cosy.util;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * jks证书处理工具类
 *
 * @author ithuameng
 */
public class SSLContextUtil {

    private static volatile SSLContext sslContext = null;

    public static SSLContext createSSLContext(String type, String path, String password) throws Exception {
        if (null == sslContext) {
            synchronized (SSLContextUtil.class) {
                if (null == sslContext) {
                    // 支持JKS、PKCS12
                    KeyStore ks = KeyStore.getInstance(type);
                    // 证书存放地址
                    InputStream ksInputStream = new FileInputStream(path);
                    ks.load(ksInputStream, password.toCharArray());
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, password.toCharArray());
                    sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(kmf.getKeyManagers(), null, null);
                }
            }
        }
        return sslContext;
    }

    private SSLContextUtil() {
    }
}
